package cn.milai.amtc.step6;

import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import cn.milai.amtc.Audio;

/**
 * 添加 code 标识音频，同 code 重复播放将替换未播放完的音频，实现最终优化
 */
public class AudioManager {

	private static final int THREAD_NUM = 3;
	private static final int PER_FRAMES = 16;
	private static final ExecutorService threadPool;

	private static Queue<Audio> audios = new ConcurrentLinkedQueue<>();
	private static Queue<Audio> playing = new ConcurrentLinkedQueue<>();

	static {
		threadPool = Executors.newFixedThreadPool(THREAD_NUM);
		new Thread() {
			public void run() {
				while (true) {
					{
						for (Audio a : audios) {
							if (playing.contains(a)) {
								continue;
							}
							if (a.isComplete()) {
								audios.remove(a);
							} else {
								playing.add(a);
								threadPool.execute(() -> {
									a.play(PER_FRAMES);
									playing.remove(a);
								});
							}
						}
					}
				}
			};
		}.start();
	}

	public static void add(Audio audio) {
		for (Audio a : audios) {
			if (a.getCode().equals(audio.getCode())) {
				audios.remove(a);
			}
		}
		audios.add(audio);
	}

	public static void play() {
	}
}
